package org.gten.gegedexin.service;

import org.gten.gegedexin.dao.TokenDao;
import org.gten.gegedexin.pojo.TokenPojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.core.Local;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
/**
 * @author Eric
 * @date 2023/6/29
 */
@Service
public class TokenServiceImpl {
    @Autowired
    TokenDao tokenDao;

    public void addToken(String account , String token, LocalDateTime time, int limit){
        tokenDao.insert(new TokenPojo(token, account, time, limit));
    }

    public void updateTime(String token){
        TokenPojo tokenPojo = new TokenPojo() ;
        tokenPojo.setToken(token);
        tokenPojo.setTime(LocalDateTime.now());

        // 下班
        // 下班二
        tokenDao.updateById(tokenPojo);
    }


    public String getAccount(String token){
        if(tokenDao.selectById(token) == null){
            return null;
        }

        return tokenDao.selectById(token).getAccount();
    }

    public TokenPojo getTokenByToken(String token){
        return tokenDao.selectById(token);
    }

    public boolean judgeOutOfTime(String token){
        TokenPojo tokenPojo = tokenDao.selectById(token);
        if(tokenPojo == null){
            return false;
        }
        System.out.println(tokenPojo);

        LocalDateTime dateTime = tokenPojo.getTime();
        LocalDateTime now = LocalDateTime.now(); // 获取当前时间
        Duration duration = Duration.between(dateTime, now); // 计算时间差
        long secondsDifference = Math.abs(duration.getSeconds()); // 获取时间差的绝对值，转换为秒

        if(secondsDifference <= tokenPojo.getLimit()){
            return true;
        }
        else{
            tokenDao.deleteById(token);
            return false;
        }
    }

}

